﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Xml.XPath;
using System.Xml;
using System.Xml.Linq;
using System.Linq;
using Microsoft.SharePoint.WebPartPages;

namespace Mathoms.iSharePoint
{
    using WebParts = System.Web.UI.WebControls.WebParts;

    public partial class WebPartGallery : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Web;
            SPList gallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);

            WebPartPage webPage = (WebPartPage)this.Page;

            SPWebPartManager wpManager = (SPWebPartManager)WebParts.WebPartManager.GetCurrentWebPartManager(webPage);

            var data = from SPListItem spItem in gallery.Items
                       /* where !string.IsNullOrEmpty((string)spItem.Properties["Group"])
                                && (((string)spItem.Properties["Group"] == "Right Zone")
                                || ((string)spItem.Properties["Group"] == "Center Zone"))*/

                       select new
                       {
                           CssClass = "mis-gallery-web-part ui-state-highlight  draggable",
                           Text = spItem.Title,                         
                           wpDef = GetWebPartDefinitionXml(spItem),
                           BackGroundImage = GetCatalogIconUrl(spItem),
                       };
            Gallery.DataSource = data;
            Gallery.DataBind();

        }

        private string GetWebPartDefinitionXml(SPListItem spItem)
        {
            System.IO.Stream fileStream = spItem.File.OpenBinaryStream();
            string xml = (new System.IO.StreamReader(spItem.File.OpenBinaryStream())).ReadToEnd();
            return Server.HtmlEncode(xml);
        }

        private string GetCatalogIconUrl(SPListItem spItem)
        {
            System.IO.Stream fileStream = spItem.File.OpenBinaryStream();
            string xml = (new System.IO.StreamReader(spItem.File.OpenBinaryStream())).ReadToEnd();
            XmlDocument document = new XmlDocument();
            document.InnerXml = xml;

            // Set up namespace manager for XPath  
            XmlNamespaceManager ns = new XmlNamespaceManager(document.NameTable);
            XmlNode node;

            if (System.IO.Path.GetExtension(spItem.File.Name) == ".webpart")
            {
                ns.AddNamespace("wp", "http://schemas.microsoft.com/WebPart/v3");
                node = document.SelectSingleNode("/webParts/wp:webPart/wp:data/wp:properties/wp:property[@name='CatalogIconUrl']", ns);
                if (node != null)
                {
                    return "/" + node.InnerText;
                }
            }
            else
            {
                ns.AddNamespace("wp", "http://schemas.microsoft.com/WebPart/v2");
                node = document.SelectSingleNode("/wp:WebPart/wp:PartImageLarge", ns);
                if (node != null)
                {
                    return node.InnerText;
                }
            }         

            return "/_layouts/images/webpart.gif";
        }

        private string GetDescription(SPListItem spItem)
        {
            System.IO.Stream fileStream = spItem.File.OpenBinaryStream();
            string xml = (new System.IO.StreamReader(spItem.File.OpenBinaryStream())).ReadToEnd();
            XmlDocument document = new XmlDocument();
            document.InnerXml = xml;

            // Set up namespace manager for XPath  
            XmlNamespaceManager ns = new XmlNamespaceManager(document.NameTable);
            ns.AddNamespace("wp", "http://schemas.microsoft.com/WebPart/v3");

            XmlNode node = document.SelectSingleNode("/webParts/wp:webPart/wp:data/wp:properties/wp:property[@name='Description']", ns);

            if (node != null)
            {
                return node.InnerText;
            }
            return string.Empty;
        }

    }
}
